import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { getUploadToken } from '../services/qiniu';
import { submitImage } from '../services/register';
import { getLocalStorage } from '../utils/storage';

export default {
  namespace: 'doctorImage',
  state: {
    uploadToken: '',
    imageUrl: '',
    buttonStatus: true,
  },
  reducers: {
    uploadImageSuccess(state, { payload }) {
      return { ...state, buttonStatus: false, imageUrl: payload };
    },
    fetchUploadTokenSuccess(state, { payload }) {
      return { ...state, uploadToken: payload };
    },
  },
  effects: {
    *fetchUploadToken({ payload }, { call, put }) {
      const { data } = yield call(getUploadToken, payload);
      yield put({
        type: 'fetchUploadTokenSuccess',
        payload: data.token,
      });
    },
    *submitImage({ payload }, { select, call, put }) {
      const image = yield select(({ doctorImage }) => doctorImage.imageUrl);
      const { err } = yield call(submitImage, {
        image,
      });
      if (!err) {
        yield put(routerRedux.push('/uploadDoctorLic'));
      } else {
        err.json.then(errJson => alert(errJson.errMessage));
      }
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/uploadDoctorImage').exec(location.pathname);
        if (match) {
          const token = getLocalStorage('access_token');
          if (token) {
            dispatch({
              type: 'fetchUploadToken',
              payload: {
                token,
                bucket: 'memberdata',
                insertOnly: 0,
              },
            });
          }
        }
      });
    },
  },
};
